package com.starwiz.po;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.core.app.NotificationManagerCompat;
import android.content.Intent;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements TencentLocationListener {

    private Button checkPositionBtn;
    private TencentLocationManager mLocationManager;

    private static final String NOTIFICATION_CHANNEL_NAME = "locationdemoBackgroundLocation";
    private static final int LOC_NOTIFICATIONID = 100;
    /**
     * 使用一个标志, 防止 requestLocationUpdates 和 removeUpdates 被多次重复调用.
     * (注,多次调用不会产生任何问题)
     */
    private boolean mStarted = false;
    private boolean isCreateChannel;
    private NotificationManager notificationManager;
    private int mInterval = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPositionBtn = findViewById(R.id.check_position_btn);
        checkPositionBtn.setOnClickListener(v -> {
            // 检查位置权限
            if (ActivityCompat.checkSelfPermission(v.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // 权限未被授予，请求权限
                ActivityCompat.requestPermissions((Activity) v.getContext(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {

                // 检查通知权限是否已经授予
                boolean notificationPermissionGranted = NotificationManagerCompat.from(this).areNotificationsEnabled();

                if (!notificationPermissionGranted) {
                    // 请求通知权限
                    Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                            .putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
                    startActivity(intent);
                }

                TencentLocationManager.setUserAgreePrivacy(true);
                mLocationManager = TencentLocationManager.getInstance(v.getContext());
                TencentLocationRequest request = TencentLocationRequest.create();
                //用户可以自定义定位间隔，时间单位为毫秒，不得小于1000毫秒:
                request.setInterval(10000);
                //设置请求级别
                request.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
                //是否允许使用GPS
                request.setAllowGPS(true);
                //是否需要获取传感器方向
                request.setAllowDirection(false);
                //是否需要开启室内定位
                request.setIndoorLocationMode(true);
                // 设置定位模式
                int locMode = TencentLocationRequest.HIGH_ACCURACY_MODE;
                request.setLocMode(locMode);
//                mLocationManager.requestLocationUpdates(request,this);
                mLocationManager.enableForegroundLocation(LOC_NOTIFICATIONID, buildNotification());
                mLocationManager.requestLocationUpdates(request, this, getMainLooper());
            }
        });
    }

    @Override
    public void onLocationChanged(TencentLocation location, int error, String reason) {
        // do your work
        Log.i("定位位置", location.getLatitude() + " - " + location.getLongitude());
        FetchDataAsyncTask  task = new FetchDataAsyncTask(location);
        task.execute();
    }

    @Override
    public void onStatusUpdate(String name, int status, String desc) {
        // do your work
        //Log.i("定位状态", name + " " + status + " " + desc);
    }

    class FetchDataAsyncTask extends AsyncTask<Void, Void, String> {
        TencentLocation location;
        private final String USER_AGENT = "Mozilla/5.0";
        private final String SERVER_ENDPOINT = "http://152.136.149.151:8855/app-test";

        private String createJsonPayload(double latitude, double longitude) {
            // 创建JSON请求体
            String json = String.format("{\"latitude\": %f, \"longitude\": %f}", latitude, longitude);
            return json;
        }

        public FetchDataAsyncTask(TencentLocation location){
            this.location = location;
        }

        @Override
        protected String doInBackground(Void... voids) {
            String json = createJsonPayload(location.getLatitude(), location.getLongitude());
            try {
                URL url = new URL(SERVER_ENDPOINT);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept-Charset", "UTF-8");
                conn.setDoOutput(true);

                // 发送POST请求的body
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(json);
                wr.flush();
                wr.close();

                // 检查响应码
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    return response.toString();
                } else {
                    return "HTTP ERROR " + responseCode;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "ERROR:" + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // 在这里更新UI，例如显示获取到的数据
            Log.d("NetworkResult", "Data: " + result);
            try {
                JSONObject resultObject = new JSONObject(result);
                if(resultObject.getInt("code") == 200){
                    JSONObject dataObject = resultObject.getJSONObject("data");
                    String remark = dataObject.getString("remark");
                    String isRisk = dataObject.getString("isRisk");
                    String risk = dataObject.getString("risk");
                    String message = "";
                    if("1".equals(isRisk)){
                        message = "警告：当前处于" + remark +" ，风险等级：" + risk;
                    }else{
                        message = "当前区域无风险";
                    }
                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private Notification buildNotification() {
        Notification.Builder builder = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (notificationManager == null) {
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("LocationDemo")
                .setContentText("正在后台运行")
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            notification = builder.getNotification();
        }
        return notification;
    }

}